package scatter.wwd.rest.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import scatter.area.pojo.po.Area;
import scatter.area.rest.service.IAreaService;
import scatter.common.ErrorCode;
import scatter.common.LoginUser;
import scatter.common.dict.PublicDictEnums;
import scatter.common.pojo.form.BasePageQueryForm;
import scatter.common.rest.exception.BusinessException;
import scatter.common.rest.service.IBaseAddUpdateQueryFormServiceImpl;
import scatter.dict.pojo.po.Dict;
import scatter.dict.rest.service.IDictService;
import scatter.recommend.rest.recommend.IRecommendFramework;
import scatter.recommend.rest.recommend.dto.RecommendResultDto;
import scatter.wwd.pojo.form.*;
import scatter.wwd.pojo.po.UserInfo;
import scatter.wwd.rest.WwdErrorCode;
import scatter.wwd.rest.mapper.UserInfoMapper;
import scatter.wwd.rest.service.IUserInfoService;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户信息表 服务实现类
 * </p>
 *
 * @author yw
 * @since 2020-12-08
 */
@Service
@Transactional
public class UserInfoServiceImpl extends IBaseAddUpdateQueryFormServiceImpl<UserInfoMapper, UserInfo, UserInfoAddForm, UserInfoUpdateForm, UserInfoPageQueryForm> implements IUserInfoService {


    @Lazy
    @Autowired
    private IRecommendFramework iRecommendFramework;

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private IDictService iDictService;

    @Autowired
    private IAreaService iAreaService;

    @Value("${scatter.wwdUserRecommendNum:10}")
    private Integer wwdUserRecommendNum = 10;


    @Override
    public void preAdd(UserInfoAddForm addForm, UserInfo po) {
        super.preAdd(addForm, po);

    }

    @Override
    public void preUpdate(UserInfoUpdateForm updateForm, UserInfo po) {
        super.preUpdate(updateForm, po);

    }

    @Override
    public List<UserInfo> recommend(LoginUser loginUser, UserInfoPageQueryForm queryForm) {

        // 如果用户未登录 推荐三个用户即可
        int limit = wwdUserRecommendNum;

        String loginUserId = null;
        if (loginUser != null) {
            loginUserId = loginUser.getId();
        }

        List<RecommendResultDto> recommendResultDtos = iRecommendFramework.recommend(loginUserId, 10, "wwdUser");
        List<String> collect = recommendResultDtos.stream().map(RecommendResultDto::getItemId).collect(Collectors.toList());
        if (isEmpty(collect)) {
            return null;
        }
        return getByUserIds(collect);

    }

    @Override
    public IPage<UserInfo> getPageBySameCity(UserInfoPageSameCityQueryForm queryForm) {

        String genderDictId = null;

        UserInfo byUserId = getByUserId(queryForm.getUserId());
        genderDictId = byUserId.getGenderDictId();
        String anotherGenderDictId = getAnotherGenderDictId(genderDictId);
        if (isStrEmpty(anotherGenderDictId)) {
            throw new BusinessException("个人资料中缺少性别信息哦，先去完善吧",true, ErrorCode.ERROR_NO_GENER.getCode());
        }
        if (isStrEmpty(byUserId.getNowAreaId())) {
            throw new BusinessException("个人资料中缺少当前所在地信息，先去完善吧",true, WwdErrorCode.ERROR_NO_NOW_AREA.getCode());
        }
        // 获取城市对应区县
        Area byId = iAreaService.getById(byUserId.getNowAreaId());
        // byId.getParentId() 为城市id
        List<String> collect = iAreaService.getChildren(byId.getParentId()).stream().map(Area::getId).collect(Collectors.toList());
        Page pageQuery = new Page(((BasePageQueryForm) queryForm).getCurrent(), ((BasePageQueryForm) queryForm).getSize());

        return page(pageQuery,Wrappers.<UserInfo>lambdaQuery().eq(UserInfo::getGenderDictId,genderDictId).in(UserInfo::getNowAreaId,collect));
    }

    /**
     * 获取异性性别
     *
     * @param genderDictId
     * @return
     */
    public String getAnotherGenderDictId(String genderDictId) {
        if (isStrEmpty(genderDictId)) {
            return null;
        }

        // 获取要查询的字典id
        String queryGenderDictId = null;


        if (!isStrEmpty(genderDictId)) {
            Dict byId = iDictService.getById(genderDictId);
            if (byId != null) {
                if (isEqual(PublicDictEnums.DictGender.f.itemValue(), byId.getValue())) {
                    queryGenderDictId = iDictService.getIdByGroupCodeAndValue(PublicDictEnums.DictGenderGroupCode.gender.groupCode(), PublicDictEnums.DictGender.m.itemValue());
                } else if (isEqual(PublicDictEnums.DictGender.m.itemValue(), byId.getValue())) {
                    queryGenderDictId = iDictService.getIdByGroupCodeAndValue(PublicDictEnums.DictGenderGroupCode.gender.groupCode(), PublicDictEnums.DictGender.f.itemValue());
                }
            }
        }

        return queryGenderDictId;
    }

}
